package fun.eliauk.treedemo.service.poi;

import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.xwpf.usermodel.*;


public class Test {
    public static void main(String[] args) throws IOException {
        XWPFDocument document = new XWPFDocument(new FileInputStream("D:\\project\\git_repo\\java-demo\\src\\main\\java\\fun\\eliauk\\treedemo\\service\\policy\\中国-东盟产业合作区政策摘要汇编.docx"));
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        List<Policy> policyList = new ArrayList<>();

        for (XWPFParagraph paragraph : paragraphs) {
            Policy policy = new Policy();
            String text = paragraph.getText();

            // 原始内容
            String rawData = text.substring(text.indexOf("．") + 1);
            policy.setOriginalText(rawData);
            System.out.println("政策原始内容：" + rawData);

            // 提取政策标题 （第一个句号前为政策标题）
            int firstPeriodIndex = text.indexOf("。");
            if (firstPeriodIndex != -1) { // 确保字符串中确实包含句号
                String title = text.substring(text.indexOf("．") + 1, firstPeriodIndex);
                System.out.println("政策标题：" + title);

                policy.setPolicyTitle(title);
                policy.setOriginalTitle(title);
            }

            //提取政策内容
            int i = text.indexOf("《");
            if (i != -1) {
                String content = text.substring(firstPeriodIndex + 1, i);
                policy.setPolicyContent(content);
            }


            // 提取政策文件
            Pattern bookpattern = Pattern.compile("《(.*?)》");
            Matcher bookMatcher = bookpattern.matcher(text);
            if (bookMatcher.find()) {
                String bookTitle = "《" + bookMatcher.group(1) + "》"; // 获取匹配到的内容
                System.out.println("政策文件: " + bookTitle);
                policy.setPolicyFile(bookTitle);
            }

            // 提取政策凭证
            String year = null;
            Pattern proofPattern = Pattern.compile("（[^）]*号）");
            Matcher proofMatcher = proofPattern.matcher(text);
            if (proofMatcher.find()){
                String policyProof = proofMatcher.group(0);
                System.out.println("政策凭证: " + policyProof);
                policy.setPolicyProof(policyProof);
                Pattern yearPattern = Pattern.compile("（.*?([0-9]{4}).*?）");
                Matcher yearMatcher = yearPattern.matcher(policyProof);
                if (yearMatcher.find()) {
                    year = yearMatcher.group(1);
                    System.out.println("发布年号: " + year);
                    System.out.println("有效期开始日期：" + year + "-01-01");
                    policy.setProofYear(year);
                    policy.setBeginDate(year + "-01-01");
                }
            }

            // 提取有效期限 (1)
            Pattern timepattern = Pattern.compile("有效期(\\\\d{1,2}|[一二三四五六七八九十]{1,2})年。");
            Matcher timeMatcher = timepattern.matcher(text);
            if (timeMatcher.find()) {
                String extractedNumber = timeMatcher.group(1); // 获取匹配到的数字 有可能是 阿拉伯 也有 中文
                String validityPeriod = extractedNumber;

                // 判断提取到的数字是否包含中文数字字符
                Pattern chinesePattern = Pattern.compile("[一二三四五六七八九十]");
                Matcher chineseMatcher = chinesePattern.matcher(extractedNumber);
                if (chineseMatcher.find()) { //中文
                    validityPeriod = convertChineseToArabic(extractedNumber);
                }

                System.out.println("有效期限: " + validityPeriod + "年");
                policy.setLongTime(validityPeriod);
                if (year != null) {
                    Integer yearInt = Integer.valueOf(year) - 1 + Integer.valueOf(validityPeriod);
                    System.out.println("有效期结束日期: " + yearInt + "-12-31");

                    policy.setEndDate(yearInt + "-12-31");
                }
            }


            // 提取有效期限 (2)
            Pattern datePattern = Pattern.compile("有效期(\\d{4}年\\d{1,2}月\\d{1,2}日)至(\\d{4}年\\d{1,2}月\\d{1,2}日)");
            Matcher dataMatcher = datePattern.matcher(text);

            if (dataMatcher.find()) {
                String startDate = dataMatcher.group(1);
                String endDate = dataMatcher.group(2);


                System.out.println("有效期开始日期: " + toNumberDate(startDate));
                System.out.println("有效期结束日期: " + toNumberDate(endDate));

                policy.setBeginDate(toNumberDate(startDate));
                policy.setEndDate(toNumberDate(endDate));

                // 有效期限
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate date1 = LocalDate.parse(toNumberDate(startDate));
                LocalDate date2 = LocalDate.parse(toNumberDate(endDate));
                int longTime = date2.getYear() - date1.getYear()  + 1;
                policy.setLongTime(String.valueOf(longTime));
            }


            // 提取有效期（3）
            Pattern pattern = Pattern.compile("有效期(\\\\d{4})年至(\\\\d{4})年");
            Matcher matcher = pattern.matcher(text);
            if (matcher.find()){
                String startDate = matcher.group(1);
                String endDate = matcher.group(2);

                policy.setBeginDate(startDate + "-01-01");
                policy.setEndDate(endDate+"-12-31");
            }


            // 备注
            if (text.length()-1!=-1){
                if (text.charAt(text.length() - 1) == '。') {
                    String note = text.substring(text.lastIndexOf('，')+1);
                    if (!note.contains("有效")){
                        policy.setNote(note);
                    }
                }
            }

            policyList.add(policy);


            System.out.println();
            System.out.println();
            System.out.println();
        }

        MyExcelExportUtil.exportExcel(policyList, Policy.class, "政策基本信息", "政策数据", null);
        document.close();
    }


    public static String convertChineseToArabic(String chineseNumber) {
        switch (chineseNumber) {
            case "零":
                return "0";
            case "一":
                return "1";
            case "二":
                return "2";
            case "三":
                return "3";
            case "四":
                return "4";
            case "五":
                return "5";
            case "六":
                return "6";
            case "七":
                return "7";
            case "八":
                return "8";
            case "九":
                return "9";
            case "十":
                return "10";
            default:
                return chineseNumber;
        }
    }


    public static String toNumberDate(String originalDate) {
        // 将原始日期字符串转换为LocalDate对象
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年M月d日");
        LocalDate date = LocalDate.parse(originalDate, formatter);

        // 将LocalDate对象格式化为需要的日期字符串格式
        String formattedDate = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        return formattedDate;
    }
}
